'use strict';

/* Controllers */
app.controller('firstExamineCtrl', function($scope, $http, rest, $compile, $location, tipService, ngDialog, user, $state, $window, uiLoad, $rootScope, $ocLazyLoad, $timeout) {

    var token = $window.localStorage.getItem("token");
    var userId = $window.localStorage.getItem("id");

    //方法级权限
    var accessStr = $window.localStorage.getItem("accessStr");
    $scope.btns = {
            add: 'innjia', //新建
            delete: 'innjia', //删除
            edit: 'innjia', //编辑
            jurisdiction: 'innjia', //权限分配
            resetPasswords: 'innjia', //重置密码
            addmember: 'innjia', //添加成员
            exportExcel: 'innjia', //导出表格
            batchExportImg: 'innjia', //批量导出图片
            details: 'innjia', //详情
            rent: 'innjia', //租赁PDF
            list: 'innjia', //列表
            batchApproval: 'innjia', //批量审批
            batchClaim: 'innjia' //批量认领
        }
        //延迟执行 - 当左侧菜单生产完毕再获取当前菜单的ID 利用ui-sref-active有且只有一个active即当前的特性用jq去获取预先存储在菜单上的id
    user.response().then(function(res) {
        var nowId = $(document).find(".navItem.active").attr("data-id");
        rest.decoJava({
            type: "post",
            url: "/tenancy-sys/admin/menu/detail/" + nowId,
            data: "",
            //contentType:"application/json",
            beforeSend: function(request) {
                request.setRequestHeader("token", token);
            },
            success: function(data) {
                console.log(data)
                if (data.code == "0000") {
                    //匹配权限
                    angular.forEach(data.result.menuMethods, function(data) {
                        if (data.methodTagName == "add") {
                            $scope.btns.add = data.id;
                        } else if (data.methodTagName == "delete") {
                            $scope.btns.delete = data.id;
                        } else if (data.methodTagName == "edit") {
                            $scope.btns.edit = data.id;
                        } else if (data.methodTagName == "jurisdiction") {
                            $scope.btns.jurisdiction = data.id;
                        } else if (data.methodTagName == "resetPasswords") {
                            $scope.btns.resetPasswords = data.id;
                        } else if (data.methodTagName == "addmember") {
                            $scope.btns.addmember = data.id;
                        } else if (data.methodTagName == "exportExcel") {
                            $scope.btns.exportExcel = data.id;
                        } else if (data.methodTagName == "batchExportImg") {
                            $scope.btns.batchExportImg = data.id;
                        } else if (data.methodTagName == "details") {
                            $scope.btns.details = data.id;
                        } else if (data.methodTagName == "rent") {
                            $scope.btns.rent = data.id;
                        } else if (data.methodTagName == "list") {
                            $scope.btns.list = data.id;
                        } else if (data.methodTagName == "batchApproval") {
                            $scope.btns.batchApproval = data.id;
                        } else if (data.methodTagName == "batchClaim") {
                            $scope.btns.batchClaim = data.id;
                        }
                    })
                } else if (data.message == "菜单Id有误！！！") {
                    // $window.location.reload();
                } else {
                    layer.msg(data.message + '请刷新试试', {
                        offset: 't',
                        icon: 2
                    });
                }
            }
        });

    })

    $scope.queryParams = {
        _landlordPhone: "",
        _areaName: "",
        _roomCode: "",
        _landlordName: "",
        dateStart: "",
        dateEnd: "",
        houseProcessStatus: "",
        shopProvinceId: "",
        shopCityId: ""
    };
    $scope.checkTypeArray = [{
        "name": "全部",
        "value": ""
    }, {
        "name": "待初审",
        "value": "HouseFirstTrial"
    }, {
        "name": "初审中",
        "value": "HouseFirstTrialing"
    }];
    $scope.houseProcessStatus = $scope.checkTypeArray[0];

    $scope.houseProcessStatus.selected = {
        name: "请选择审核状态",
        id: ""
    }
    $scope.provinceId = {
        name: "请选择省份",
        id: ""
    }
    $scope.cityId = {
        name: "请选择城市",
        id: ""
    }

    var tmpHouseIdArr = "";
    rest.decoJava({
        type: "post",
        url: "/tenancy-sys/communal/getAddress",
        data: {
            addressId: 0,
        },
        success: function(data) {
            $scope.provinceList = data.result;
            // console.log($scope.provinceList);
        }
    });

    $scope.chooseProvince = function(index, provinceList) {
        console.log(provinceList[index]);
        $scope.queryParams.shopProvinceId = provinceList[index].id;
        var shopCityId = $scope.queryParams.shopProvinceId;
        rest.decoJava({
            type: "post",
            url: "/tenancy-sys/communal/getAddress",
            data: {
                addressId: shopCityId,
            },
            success: function(data) {
                $scope.cityList = data.result;
                // console.log($scope.cityList);
            }
        });
    }
    $scope.chooseCity = function(index, cityList) {
        $scope.queryParams.shopCityId = cityList[index].id;
    }
	
	var tabHeight = ($window.innerHeight - 415) + "px"; //table内容区高度
    initDataTables();
    function initDataTables() {
        $scope.dataTableFirstList = {
            "sAjaxSource": "/tenancy-sys/admin/house/index",
            "sScrollY": tabHeight, //给定高度，内容超出即出滚动条
	        "bScrollCollapse": false, //不管内容多少高度固定
            "bAutoWidth": true,
            "aLengthMenu": [25, 50, 100, 200],
            "iDisplayLength": 25,
            "sScrollY": tabHeight, //给定高度，内容超出即出滚动条
            "bScrollCollapse": false, //不管内容多少高度固定
            "sDom": '<"top">rt<"bottom"lip><"clear">', //位置 l-每页显示数量,f-过滤输入,t-表单Table,i-信息,p-翻页
            "aoColumns": [{
                "mDataProp": "",
                "sDefaultContent": "",
                "sClass": "center handle-ck"
            }, {
                "mDataProp": "createTime",
                "sTitle": "创建时间",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "city",
                "sTitle": "城市",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "region",
                "sTitle": "区县",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "districtName",
                "sTitle": "小区名字",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "street",
                "sTitle": "详细地址",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "roomNo",
                "sTitle": "房间号",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "landlordMobile",
                "sTitle": "房东手机号",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "landlordName",
                "sTitle": "房东姓名",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "houseProcessStatus",
                "sTitle": "审核状态",
                "sDefaultContent": "",
                "sClass": "center houseStatus"
            }, {
                "mDataProp": "operate",
                "sTitle": "操作",
                "sDefaultContent": "",
                "sClass": "center handle-td operation"
            }],
            "fnRowCallback": function(nRow, aData, iDisplayIndex) {
                var btnStr = "";

                //指派先不要了 <dd><a href='javascript:' ng-click='assignTo(\"" + aData.id + "\")'>指派</a></dd>\
                btnStr += " <a class='operation-btn'>\
                                <img src='img/operation.png' width='20px' height='20px' />\
                                <div class='operation-none' >\
                                    <dl class='operation oper-triangle'>\
                                        <dd><a href='javascript:' data-btn='btns.details' ng-click='viewHouseDetails(\"" + aData.id + "\")'>房源详情</a></dd>\
                                        <span class='z'>▲</span><span class='y'>▲</span>\
                                    </dl>\
                                </div>\
                            </a>";


                $(nRow).find(".handle-td").append($compile(btnStr)($scope));

                $(nRow).find(".operation-btn").on('click', function() {
                    var sopt = $(this).parent().find(".operation-none");
                    if (sopt.css('display') == 'none') {
                        sopt.show();
                        $scope.isCoverBgShow = true;
                        $scope.$apply();
                    } else {
                        sopt.hide();
                        $scope.isCoverBgShow = false;
                        $scope.$apply();
                    }
                });

                var checkStr = "";
                checkStr += '<input type="checkbox" data-index="' + iDisplayIndex + '" value="' + $scope.myDatas.result.models[iDisplayIndex].id + '" data-assignedUserId="' + $scope.myDatas.result.models[iDisplayIndex].assignedUserId + '" class="checkchild" />';
                $(nRow).find(".handle-ck").append($compile(checkStr)($scope));

                if (aData.houseProcessStatus == "HouseFirstTrial") {
                    var statusStr = "待初审";
                } else if (aData.houseProcessStatus == "HouseFirstTrialing") {
                    var statusStr = "初审中";
                } else if (aData.houseProcessStatus == "HouseFirstTrialSuccess") {
                    var statusStr = "初审通过";
                } else if (aData.houseProcessStatus == "HouseBack") {
                    var statusStr = "初审拒绝";
                } else if (aData.houseProcessStatus == "HouseDecorateAssessment") {
                    var statusStr = "待装修评估";
                } else if (aData.houseProcessStatus == "HouseDecorateAssessmenting") {
                    var statusStr = "装修评估中";
                } else if (aData.houseProcessStatus == "HouseDecorateAssessmentSuccess") {
                    var statusStr = "装修评估通过";
                } else if (aData.houseProcessStatus == "HouseJudgment") {
                    var statusStr = "待终审";
                } else if (aData.houseProcessStatus == "HouseJudgmenting") {
                    var statusStr = "终审中";
                } else if (aData.houseProcessStatus == "HouseJudgmentSuccess") {
                    var statusStr = "终审通过";
                } else if (aData.houseProcessStatus == "HouseJudgmentBack") {
                    var statusStr = "终审拒绝";
                } else if (aData.houseProcessStatus == "HouseJudgmentRepetition") {
                    var statusStr = "待高管审核";
                } else if (aData.houseProcessStatus == "AccountSuccessful") {
                    var statusStr = "高管审核通过";
                } else if (aData.houseProcessStatus == "HouseJudgmentRepetitionBack") {
                    var statusStr = "高管审核拒绝";
                } else if (aData.houseProcessStatus == "HouseSupplement") {
                    var statusStr = "补件";
                } else if (aData.houseProcessStatus == "HouseClaim") {
                    var statusStr = "认领";
                } else if (aData.houseProcessStatus == "HOUSEASSIGN") {
                    var statusStr = "指派";
                }

                $(nRow).find(".houseStatus").empty().append(statusStr);

                tmpHouseIdArr += aData.houseId + ",";
                if (iDisplayIndex >= 9) {
                    // console.log(tmpHouseIdArr);
                }
            },
            "fnDrawCallback": function(oSettings) {
                $scope.houseProcessStatusValue = $scope.queryParams.houseProcessStatus;
                if ("number" == typeof $scope.houseProcessStatusValue) {
                    $scope.checkTypeArray.map(function(ele, index) {
                        if ($scope.houseProcessStatusValue == ele.value) {
                            $scope.houseProcessStatus.selected = ele;
                        }
                    })
                }
                $scope.decorateStatusValue = $scope.queryParams.decorateStatus;
                if ("number" == typeof $scope.decorateStatusValue) {
                    $scope.lockTypeArray.map(function(ele, index) {
                        if ($scope.decorateStatusValue == ele.value) {
                            $scope.decorateStatus.selected = ele;
                        }
                    })
                }

            },
            "fnServerParams": function(aoData) {


                if ($scope.houseProcessStatus && $scope.houseProcessStatus.selected) {
                    $scope.queryParams.houseProcessStatus = $scope.houseProcessStatus.selected.value
                }
                if ($scope.decorateStatus && $scope.decorateStatus.selected) {
                    $scope.queryParams.decorateStatus = $scope.decorateStatus.selected.value
                }
                aoData.push({
                    'name': 'queryParams',
                    'value': $scope.queryParams
                });

                return aoData;
            },
            "fnServerData": function(sSource, aData, fnCallback, dataTableObject) {
                //自定义给datatables传递的参数
                var obj = dataTableObject.oAjaxData,
                    _baseParams = {
                        'page': obj.iDisplayStart / obj.iDisplayLength + 1,
                        'rows': obj.iDisplayLength,
                        'search': 'false',
                        'nd': '1494221804416',
                        'status': 'AVAILABLE',
                        'pageType': "HouseFirstTrial",
                    };

                var __data = angular.extend({}, _baseParams, obj.queryParams);
                rest.decoJava({
                    type: "post",
                    url: sSource,
                    data: __data,
                    beforeSend: function(request) {
                        request.setRequestHeader("token", token);
                    },
                    success: function(data) {
                        $scope.myDatas = data;
                        var data1 = {
                            'aaData': data.result.models,
                            'sEcho': obj.sEcho,
                            'iTotalDisplayRecords': data.pager.recordCount,
                            'iTotalRecords': data.records,
                        };
                        fnCallback(data1);
                        /*$(dataTableObject.nScrollBody).css('overflow', 'visible');
                        $(dataTableObject.nScrollBody).css('margin-bottom', 30 + 'px');
                        $(".dataTables_scrollHead").css("overflow","visible");*/
                       	$(".dataTables_scroll").css("overflow", "auto");
        				$(".dataTables_scrollBody").css("overflow", "visible");
        				$(".dataTables_scrollBody table").css("marginBottom", "50px");
                    }
                });

                //搜索 说明 只要是点击的搜索就让page为1 并且刷新datatables目的是回到第一页
                //说明 自定义搜索只需在点击搜索的时候改变下datatables传过去的参数 然后$scope.dataTable.fnClearTable()即可
                $scope.search = function() {
                    __data.page = 1;
                    $scope.tablefirstList.fnClearTable();
                }

            }
        }
    }

    $scope.initFinishHouseList = function(dataTable) {
        $scope.tablefirstList = dataTable;
    }

    //全部选中和取消
    $scope.allMenu = function(e) {
        var This = angular.element(e.target);
        if (This.is(":checked")) {
            angular.element(".checkchild").prop("checked", true);
        } else {
            angular.element(".checkchild").prop("checked", false);
        }
    }

    //监听房东姓名
    $scope.$watch('_landlordName', function(newValue, oldValue) {
        $scope.queryParams.landlordName = newValue;
    })

    //监听小区名称
    $scope.$watch('_areaName', function(newValue, oldValue) {
        $scope.queryParams.districtName = newValue;
    })

    //监听房间号
    $scope.$watch('_roomCode', function(newValue, oldValue) {
        $scope.queryParams.roomNo = newValue;
    })

    //房东手机号
    $scope.$watch('_landlordPhone', function(newValue, oldValue) {
        $scope.queryParams.landlordMobile = newValue;
    })

    $scope.queryUser = function() {
        if ($scope.queryParams.houseProcessStatus && $scope.queryParams.houseProcessStatus.selected) {
            var houseProcessStatusCache = $scope.queryParams.houseProcessStatus.selected;
            if ($scope.queryParams.houseProcessStatus.selected) {
                $scope.queryParams.houseProcessStatus = $scope.queryParams.houseProcessStatus.selected.value
            }
            $scope.tablefirstList.fnClearTable();
            $scope.queryParams.houseProcessStatus = {};
            $scope.queryParams.houseProcessStatus.selected = {};
            $scope.queryParams.houseProcessStatus.selected = houseProcessStatusCache;
        } else if ($scope.queryParams.decorateStatus && $scope.queryParams.decorateStatus.selected) {
            var decorateStatusCache = $scope.queryParams.decorateStatus.selected;
            if ($scope.queryParams.decorateStatus.selected) {
                $scope.queryParams.decorateStatus = $scope.queryParams.decorateStatus.selected.value
            }
            $scope.tablefirstList.fnClearTable();
            $scope.queryParams.decorateStatus = {};
            $scope.queryParams.decorateStatus.selected = {};
            $scope.queryParams.decorateStatus.selected = decorateStatusCache;
        } else {
            $scope.tablefirstList.fnClearTable();
        }

    };

    $scope.resetUser = function() {
        $scope._landlordPhone = "";
        $scope._areaName = "";
        $scope._roomCode = "";
        $scope._landlordName = "";
        $scope.houseProcessStatus.selected = undefined;
        $scope.provinceId.selected = undefined;
        $scope.cityId.selected = undefined;
        $('.searchCreateTime').val('');
        $scope.queryParams = {};
        $scope.tablefirstList.fnClearTable();
    }

    $scope.viewHouseDetails = function(id) {
        //权限控制
        var nowId = this.btns.details;
        if (accessStr.indexOf(nowId) == -1) {
            layer.msg("你没有该操作权限", {
                offset: 't',
                icon: 2
            });
            return false;
        }
        $window.localStorage.setItem('houseId', id);
        // $state.go('app.house.houseDetails', {
        //     houseId: id
        // });
        $('.operation-none').hide();
        $scope.isCoverBgShow = false;
        window.open('#/app/house/houseDetails');

    }

    $scope.assignTo = function(id) {
        ngDialog.openConfirm({
            template: 'js/module/fund/assignTo.html',
            resolve: {
                load: function() {
                    return uiLoad.load(['js/module/fund/assignTo.js'])
                }
            },
            data: {
                houseId: id
            },
            scope: $scope,
            width: 600,
            // height: 700
        }).then(function(data) {
            $scope.coverBgHide();
        }, function(reason) {
            $scope.coverBgHide();
        });
    }


    $scope.coverBgHide = function() {
        $('.operation-none').hide();
        $scope.isCoverBgShow = false;
        // $scope.$apply();
    }

    $scope.$on('contractDate.start', function(event, data) {
        $scope.queryParams.dateStart = data ? (data + " 00:00:00") : "";
        // console.log(data);
    });
    $scope.$on('contractDate.end', function(event, data) {
        $scope.queryParams.dateEnd = data ? (data + " 23:59:59") : "";
        // console.log(data);
    });

    //导出excel
    $scope.exportExcel = function() {
        //权限控制
        var nowId = this.btns.exportExcel;
        if (accessStr.indexOf(nowId) == -1) {
            layer.msg("你没有该操作权限", {
                offset: 't',
                icon: 2
            });
            return false;
        }
        if ($(".checkchild:checked").length == 0) {
            layer.msg("没有选中项", {
                offset: 't',
                icon: 2,
                time: 0, //不自动关闭
                btn: ['确定'],
                yes: function(index) {
                    layer.close(index);
                }
            });
        } else {

            //选中的数据id
            var idArr = [];
            $(".checkchild").each(function() {
                if ($(this).is(":checked")) {
                    idArr.push($(this).val());
                }
            });
            var _idstring = "";
            angular.forEach(idArr, function(data) {
                _idstring += data + ',';
            })
            var _idstring = _idstring.substring(0, _idstring.length - 1);

            ngDialog.openConfirm({
                template: 'js/module/fund/houseListExcel.html',
                resolve: {
                    load: function() {
                        return $ocLazyLoad.load('angularFileUpload').then(
                            function() {
                                return uiLoad.load(['js/module/fund/houseListExcel.js'])
                            });
                    }
                },
                data: {
                    _idstring: _idstring,
                    id: userId
                },
                scope: $scope,
                width: 1100,
                // height: 700
            }).then(function(data) {
                $scope.tablefirstList.fnClearTable();
            }, function(reason) {
                $scope.tablefirstList.fnClearTable();
            });
        }
    }

    //导出Img
    $scope.exportImg = function() {
        //权限控制
        var nowId = this.btns.batchExportImg;
        if (accessStr.indexOf(nowId) == -1) {
            layer.msg("你没有该操作权限", {
                offset: 't',
                icon: 2
            });
            return false;
        }
        // $window.localStorage.setItem('landlordIds', id);

        if ($(".checkchild:checked").length == 0) {
            layer.msg("没有选中项", {
                offset: 't',
                icon: 2,
                time: 0, //不自动关闭
                btn: ['确定'],
                yes: function(index) {
                    layer.close(index);
                }
            });
        } else {

            //选中的数据id
            var idArr = [];
            $(".checkchild").each(function() {
                if ($(this).is(":checked")) {
                    idArr.push($(this).val());
                }
            });
            var _idstring = "";
            angular.forEach(idArr, function(data) {
                _idstring += data + ',';
            })
            var _idstring = _idstring.substring(0, _idstring.length - 1);

            ngDialog.openConfirm({
                template: 'js/module/fund/exportHouseImg.html',
                resolve: {
                    load: function() {
                        return $ocLazyLoad.load('angularFileUpload').then(
                            function() {
                                return uiLoad.load(['js/module/fund/exportHouseImg.js'])
                            });
                    }
                },
                data: {
                    _idstring: _idstring,
                },
                scope: $scope,
                width: 1200,
                // height: 700
            }).then(function(data) {
                $scope.dataTable.fnClearTable();
            }, function(reason) {
                $scope.dataTable.fnClearTable();
            });

        }
    }

    //批量认领
    $scope.largeClaim = function() {
        //权限控制
        var nowId = this.btns.batchClaim;
        if (accessStr.indexOf(nowId) == -1) {
            layer.msg("你没有该操作权限", {
                offset: 't',
                icon: 2
            });
            return false;
        }
        if ($(".checkchild:checked").length == 0) {
            layer.msg("没有选中项", {
                offset: 't',
                icon: 2,
                time: 0, //不自动关闭
                btn: ['确定'],
                yes: function(index) {
                    layer.close(index);
                }
            });
        } else {

            //选中的数据id
            var idArr = [];
            $(".checkchild").each(function() {
                if ($(this).is(":checked")) {
                    idArr.push($(this).val());
                }
            });
            var _idstring = "";
            angular.forEach(idArr, function(data) {
                _idstring += data + ',';
            })
            var _idstring = _idstring.substring(0, _idstring.length - 1);

            ngDialog.openConfirm({
                template: 'js/module/fund/houseLargeClaim.html',
                resolve: {
                    load: function() {
                        return $ocLazyLoad.load('angularFileUpload').then(
                            function() {
                                return uiLoad.load(['js/module/fund/houseLargeClaim.js'])
                            });
                    }
                },
                data: {
                    _idstring: _idstring,
                },
                scope: $scope,
                width: 800,
                // height: 700
            }).then(function(data) {
                $scope.tablefirstList.fnClearTable();
            }, function(reason) {
                $(".checkchild").each(function() {
                    if ($(this).is(":checked") && $(this).attr("data-assignedUserId") != "null") {
                        console.log($(this).attr("data-assignedUserId"))
                        var _tr = $(this).parents("tr");
                        _tr.addClass("changeColor");
                        $timeout(function() {
                            _tr.removeClass('changeColor');
                        }, 6000)
                    }
                })
            });
        }
    }

    //初审批量审核
    $scope.firstLargeExamine = function() {
        //权限控制
        var nowId = this.btns.batchApproval;
        if (accessStr.indexOf(nowId) == -1) {
            layer.msg("你没有该操作权限", {
                offset: 't',
                icon: 2
            });
            return false;
        }
        if ($(".checkchild:checked").length == 0) {
            layer.msg("没有选中项", {
                offset: 't',
                icon: 2,
                time: 0, //不自动关闭
                btn: ['确定'],
                yes: function(index) {
                    layer.close(index);
                }
            });
        } else {

            //选中的数据id
            var idArr = [];
            $(".checkchild").each(function() {
                if ($(this).is(":checked")) {
                    idArr.push($(this).val());
                }
            });
            var _idstring = "";
            angular.forEach(idArr, function(data) {
                _idstring += data + ',';
            })
            var _idstring = _idstring.substring(0, _idstring.length - 1);

            rest.decoJava({
                type: "post",
                url: "/tenancy-sys/admin/house/skip",
                data: {
                    houseIds: _idstring,
                },
                beforeSend: function(request) {
                    request.setRequestHeader("token", token);
                },
                success: function(res) {
                    if (res.code == "0000") {
                        ngDialog.openConfirm({
                            template: 'js/module/fund/firstLargeExamine.html',
                            resolve: {
                                load: function() {
                                    return $ocLazyLoad.load('angularFileUpload').then(
                                        function() {
                                            return uiLoad.load(['js/module/fund/firstLargeExamine.js'])
                                        });
                                }
                            },
                            data: {
                                _idstring: _idstring,
                            },
                            scope: $scope,
                            width: 800,
                            // height: 700
                        }).then(function(data) {
                            $scope.tablefirstList.fnClearTable();
                        }, function(reason) {
                            $scope.tablefirstList.fnClearTable();
                        });
                    } else {
                        $(".checkchild").each(function() {
                            if ($(this).is(":checked") && $(this).attr("data-assignedUserId") == "null") {
                                console.log($(this).attr("data-assignedUserId"))
                                var _tr = $(this).parents("tr");
                                _tr.addClass("changeColor");
                                $timeout(function() {
                                    _tr.removeClass('changeColor');
                                }, 6000)
                            }
                        })
                        tipService.show("body", {
                            message: res.message,
                            notice: "danger"
                        }, 3);
                    }
                }
            })


        }
    }


});

app.controller('ContractTimeCtrl', function($scope) {
    $scope.today = function() {
        $scope.contractStartDate = "";
        $scope.contractEndDate = "";
    };

    $scope.closeAll = function() {
        $scope.openContractBeginDated =
            $scope.openContractEndDated = false;
    }

    $scope.openContractBeginDate = function($event) {
        $event.preventDefault();
        $event.stopPropagation();
        $scope.closeAll();
        $scope.openContractBeginDated = true;
    };
    $scope.openContractEndDate = function($event) {
        $event.preventDefault();
        $event.stopPropagation();
        $scope.closeAll();
        $scope.openContractEndDated = true;
    };

    $scope.dateOptions = {
        format: 'yyyy-MM-dd',
        startingDay: 1,
        class: 'datepicker'
    };

    $scope.format = 'yyyy-MM-dd';

    $scope.today();

    $scope.$watch('contractStartDate', function(newValue, oldValue) {
        if ("[object Date]" === Object.prototype.toString.call(newValue)) {
            $scope.$emit('contractDate.start', moment(newValue).format('YYYY-MM-DD'))
        } else if (null === newValue) {
            $scope.$emit('contractDate.start', '')
        }
    });
    $scope.$watch('contractEndDate', function(newValue, oldValue) {
        if ("[object Date]" === Object.prototype.toString.call(newValue)) {
            $scope.$emit('contractDate.end', moment(newValue).format('YYYY-MM-DD'))
        } else if (null === newValue) {
            $scope.$emit('contractDate.end', '')
        }
    });

});